import { validUser } from '@/utils/validate'
import { Session } from '@/utils/storage';
import { resetRouter } from "@/router/index";

export default {
  name: 'LoginBak',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUser(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '18604096523',
        password: '12345Qwe'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          Session.set('token', Math.random().toString(36).substr(0));
          
          this.$axios({
            method: "post",
            url: "api/admin/sysAdminSys/login",
            data: {
              name: this.loginForm.username,
              password: this.loginForm.password
            }
          }).then(res => {
            if (res.data.code === 200) {
              sessionStorage.setItem("uObj", JSON.stringify(res.data.data.admin));
              sessionStorage.setItem("z-admin-token", res.data.data.jwtToken);
              localStorage.setItem("z-admin-token", res.data.data.jwtToken);

              // 将当前登录人的shiroKey集合存储到sessionStorage
              sessionStorage.setItem("tRoleLists", JSON.stringify(res.data.data.admin.rights));
              sessionStorage.setItem("rolesUuid", JSON.stringify(res.data.data.admin.rolesUuid));
              sessionStorage.setItem("roleRange", res.data.data.admin.roleRange);

              console.log('login');
              // 查询菜单
              this.$axios({
                method: "get",
                url: "/api/sys/sysMenu/findMenuList"
              }).then(resN => {
                if (resN.data.code === 200) {
                  console.log('---', resN.data.data);
                  const routeData = resN.data.data;
                  sessionStorage.setItem("routeData", JSON.stringify(routeData));
                  resetRouter();

                  if (res.data.data.admin.rights.length > 0) {
                    let firstPath = "";
                    for (let i = 0; i < res.data.data.admin.rights.length; i ++) {
                      for (let j = 0; j < routeData.length; j++) {
                        if (routeData[j].shiroKey === res.data.data.admin.rights[i] 
                            // && routeData[j].fileLocation !== "ParentView" 
                            && routeData[j].icon !== null 
                            && routeData[j].icon !== "") {
                              if (routeData[j].fileLocation === "ParentView") {
                                firstPath = routeData[j].path + '/' + routeData[j].children[0].path + '';
                              } else {
                                firstPath = routeData[j].path;
                              }
                          break;
                        }
                      }
                    }
                    this.$router.push(firstPath);
                  } else {
                    this.$message({
                      message: "登录失败",
                      type: "error"
                    });
                  } 
                }
              });
            } else {
              this.$message({
                message: "登录失败",
                type: "error"
              });
            }
          }).catch(error => {
            console.log(error);
          });
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}